package vip.zhenzicheng.test.juc.lock.util;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 并发锁工具类案例
 *
 * @author zhenzicheng
 * @date 2023-02-07 12:35
 */
@Slf4j
public class CountDownLatchCase {

  @Test
  void testCountDownLatch() throws InterruptedException {
    CountDownLatch countDownLatch = new CountDownLatch(10);
    for (int i = 1; i <= countDownLatch.getCount(); i++) {
      Thread t = new Thread(() -> {
        log.info("线程「{}」正在执行任务", Thread.currentThread().getName());
        try {
          TimeUnit.SECONDS.sleep(2);
          countDownLatch.countDown();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }, "t" + i);
      t.start();
    }
    countDownLatch.await();
    System.out.println("所有任务执行结束");
  }
}
